package com.ruoyi.web.controller.power;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.baidu.Base64Util;
import com.ruoyi.common.utils.baidu.Util;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.http.HttpPostFile;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.power.voice.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/power/voice")
public class TVoiceController extends BaseController {
    @Value("${powerservice.asrurl}")
    private String asrurl;
    @Value("${powerservice.apiasr}")
    private String apiasr;
    private static final Logger log = LoggerFactory.getLogger(TVoiceController.class);

    @PostMapping("/uploadfiles")
    public AjaxResult uploadfiles(MultipartFile file) throws Exception {
        SimpleDateFormat sdf=new SimpleDateFormat("HHmmssSSS");
        String audio_name= sdf.format(new Date())+"wav";
        try {
            if(file.getSize()/1024/1024>100){
                return AjaxResult.error("上传的文件大小不能超过100 MB!");
            }

            byte[] imgdata = Util.readFileByBytes(file);
            if(imgdata==null){
                return AjaxResult.error("文件上传异常，请重新上传");
            }
            String base64Content = Base64Util.encode(imgdata);
            if(StringUtils.isEmpty(base64Content)){
                return AjaxResult.error("文件上传错误，请重新上传");
            }
            String[] arryext = {"pcm", "wav", "amr", "m4a","mp3","mp4"};
            boolean flagext = false;
            String ext = FileUploadUtils.getExtension(file);
            for (String strext : arryext) {
                if (strext.equals(ext)) {
                    flagext = true;
                }
            }
            if (flagext == false) {
                return AjaxResult.error("上传文件只能是pcm,wav,amr,m4a,mp3,mp4格式,请重新上传!");
            }
            String url = asrurl + apiasr;
            String param = "";

            VoiceAudio vaudio=new VoiceAudio();
            vaudio.setAudio_name(audio_name);
            VoiceParam reqEntity = new VoiceParam();
            reqEntity.setAudio_meta(vaudio);
            reqEntity.setAudio_data(base64Content);
            reqEntity.setSpeaker_num(1);
            param = JSON.toJSONString(reqEntity);
            String resback = HttpUtils.sendPost(url, param);
            VoiceBack backEntity = JSONObject.parseObject(resback, VoiceBack.class);
            if (backEntity != null && backEntity.getResult() != null) {
                if(backEntity.getResult().getAudio_speaker_content()!=null&&backEntity.getResult().getAudio_speaker_content().size()>0){
                    StringBuilder str=new StringBuilder();
                    for(VoiceBackContent content:backEntity.getResult().getAudio_speaker_content()){
                        if(content.getAudio_content()!=null&&StringUtils.isNotEmpty(content.getAudio_content().getContent())){
                            str.append(content.getAudio_content().getContent());
                        }
                    }
                    return AjaxResult.success(str.toString());
                }
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error("网络异常，请重新操作！");
    }
}
